# coding: utf-8
import os

from bluesky.api.index import idx_blue
from bluesky.api.resource import resource_blue
from bluesky.api.user import user_blue
from bluesky.model import schemas
from bluesky.model.resource_type_m import ResourceType
from bluesky.service.inner.resource import r_handler
from bluesky.util import json_util, biz
from extentions.db import init_db


def init_app(_app):
    _app.ctx = {}
    # 读取配置文件
    env = os.getenv('APP_ENV')
    print(f'start app environment {env}')
    if not env:
        env = 'pro'
    _app.config.from_pyfile(f'config/settings-{env}.py')
    # print('app.config.ABCDE', app.config['ABCDE'])

    # 注册接口
    register_api(_app)
    # 初始化数据库
    init_db(_app)
    # 连接数据库后需要做的初始化
    init_biz()
    # json encode
    _app.json_encoder = json_util.CJSONEncoder

    # # 注册数据库连接
    # db.bluesky = bluesky
    # db.init_app(bluesky)
    #
    # # 日志文件目录
    # if not os.path.exists(bluesky.config['LOGGING_PATH']):
    #     os.mkdir(bluesky.config['LOGGING_PATH'])
    #
    # # 日志设置
    # with open(bluesky.config['LOGGING_CONFIG_PATH'], 'r', encoding='utf-8') as f:
    #     dict_conf = yaml.safe_load(f.read())
    # logging.config.dictConfig(dict_conf)


def register_api(app):
    app.register_blueprint(idx_blue)
    app.register_blueprint(user_blue)
    app.register_blueprint(resource_blue)


def init_biz():
    init_from_db()

    r_handler.init_handler_map()


def init_from_db():
    from extentions import db
    with db.with_session() as session:
        result = session.query(ResourceType).filter(ResourceType.is_delete == 0).all()
        init_rtype(result)


def init_rtype(rs):
    for t in rs:
        ext = t.ext

        # 填充ref
        ref = ext.get('ref')
        ext_configs = ext.get('config') or []
        for cfg in ext_configs:
            return_fields = cfg.get('return_fields')
            if return_fields and ref:
                delete_fields, add_fields = [], []
                for field in return_fields:
                    if '${ref' not in field and '}' not in field:
                        continue
                    ref_key = field.replace('${ref.', '').replace('}', '')
                    ref_fields = ref.get(ref_key)
                    delete_fields.append(field)
                    add_fields.extend(ref_fields)
                list(map(lambda x: return_fields.remove(x), delete_fields))
                return_fields.extend(add_fields)

        # 设置table map
        biz.rtype_table_map[t.key] = ext.get('table')

        item = schemas.Rtype(t.id, t.key, t.name, t.ext)
        biz.resource_type_map[t.key] = item


